package com.macro.mall.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.constant.AuthConstant;
import com.macro.mall.common.domain.MinioUploadDto;
import com.macro.mall.common.domain.Oauth2TokenDto;
import com.macro.mall.common.domain.UserDto;
import com.macro.mall.common.enums.SmsTemplateEnum;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsMemberExample;
import com.macro.mall.model.UmsMemberLevel;
import com.macro.mall.model.UmsMemberLevelExample;
import com.macro.mall.portal.service.AdminService;
import com.macro.mall.portal.service.AuthService;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.portal.service.UmsMemberService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private UmsMemberLevelMapper memberLevelMapper;
    @Resource
    private UmsMemberCacheService memberCacheService;
    @Resource
    private AuthService authService;
    @Resource
    private AdminService adminService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private SmsClient smsClient;

    @Value("${sms.signName}")
    private String signName;

    @Value("${tencent.appId}")
    private String sdkAppId;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void register(UmsMember umsMember) {
        //验证验证码
        if(!verifyAuthCode(umsMember.getAuthCode(), umsMember.getPhone())){
            Asserts.fail("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(umsMember.getUsername());
        example.or(example.createCriteria().andPhoneEqualTo(umsMember.getPhone()));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("该用户已经存在");
        }
        //没有该用户进行添加操作
        umsMember.setPassword(BCrypt.hashpw(umsMember.getPassword()));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
    }

    @Override
    public CommonResult<String> generateAuthCode(String telephone, String type) {
        LOGGER.info("telephone:{},type:{}", telephone, type);
        if(!Validator.isMobile(telephone)){
            return CommonResult.failed("无效的手机号码");
        }
        String authCode = String.valueOf(RandomUtil.randomInt(100000, 999999));
        SmsTemplateEnum templateEnum = SmsTemplateEnum.findByType(type);
        if(templateEnum==null){
            return CommonResult.failed("短信类型错误");
        }
        String smsTemplateId = templateEnum.getId();
        SendSmsRequest req = new SendSmsRequest();
        req.setTemplateId(smsTemplateId);
        req.setSmsSdkAppId(sdkAppId);
        req.setSignName(signName);
        String[] phoneNumberSet = {"+86"+telephone};
        req.setPhoneNumberSet(phoneNumberSet);
        String[] templateParamSet = {authCode, "10"};
        req.setTemplateParamSet(templateParamSet);
        try {
            SendSmsResponse res = smsClient.SendSms(req);
            LOGGER.info("sendSms_result:"+ JSONUtil.toJsonStr(res));
        } catch (TencentCloudSDKException e) {
            LOGGER.error("sendSms_error", e);
            return CommonResult.failed("发送短信验证码失败");
        }
        memberCacheService.setAuthCode(telephone,authCode);
        return CommonResult.success("发送验证码成功");
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(memberList)){
            Asserts.fail("该账号不存在");
        }
        //验证验证码
        if(!verifyAuthCode(authCode, telephone)){
            Asserts.fail("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(BCrypt.hashpw(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        if(StrUtil.isEmpty(userStr)){
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
        UmsMember member = memberCacheService.getMember(userDto.getId());
        if(member!=null){
            return member;
        }else{
            member = getById(userDto.getId());
            memberCacheService.setMember(member);
            return member;
        }
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record=new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public UserDto loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);
        if(member!=null){
            UserDto userDto = new UserDto();
            BeanUtil.copyProperties(member,userDto);
            userDto.setRoles(CollUtil.toList("前台会员"));
            return userDto;
        }
        return null;
    }

    @Override
    public CommonResult<Oauth2TokenDto> login(String username, String password) {
        if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            Asserts.fail("用户名或密码不能为空！");
        }
        Map<String, String> params = new HashMap<>();
        params.put("client_id", AuthConstant.PORTAL_CLIENT_ID);
        params.put("client_secret","123456");
        params.put("grant_type","password");
        params.put("username",username);
        params.put("password",password);
        return authService.getAccessToken(params);
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(!StringUtils.hasText(authCode)){
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

    @Override
    public CommonResult<MinioUploadDto> uploadAvatar(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        LOGGER.info("fileName:{}", fileName);
        assert fileName != null;
        String extension = fileName.substring(fileName.lastIndexOf(".")+1);
        LOGGER.info("extension:{}", extension);
        if(!"jpg".equalsIgnoreCase(extension) && !"png".equalsIgnoreCase(extension) && !"jpeg".equalsIgnoreCase(extension)){
            return CommonResult.failed("上传图片格式错误");
        }
        return adminService.upload(file);
    }
}
